package per.hx.bs.sys.serviceimpl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import per.hx.bs.base.config.View;
import per.hx.bs.base.domain.ReturnDTO;
import per.hx.bs.constant.Global;
import per.hx.bs.entity.sys.SysJobDO;
import per.hx.bs.entity.sys.SysUserDO;
import per.hx.bs.entity.sys.SysUserJobDO;
import per.hx.bs.sys.dao.SysJobDao;
import per.hx.bs.sys.dao.SysUserDao;
import per.hx.bs.sys.dao.SysUserJobDao;

import java.math.BigInteger;
import java.util.*;

/**
 * @author HuXing
 * @date 2018/4/29  1:25
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping(value = "sys-service/job")
public class SysJobApiServiceImpl {

    private final
    SysJobDao jobDao;

    private final
    SysUserJobDao userJobDao;

    private final
    SysUserDao userDao;

    @Autowired
    public SysJobApiServiceImpl(SysJobDao jobDao, SysUserJobDao userJobDao, SysUserDao userDao) {
        this.jobDao = jobDao;
        this.userJobDao = userJobDao;
        this.userDao = userDao;
    }

    /**
     * 获取岗位数据
     *
     * @param map 条件
     * @return 集合
     */
    @PostMapping(value = "/listJob")
    public List<SysJobDO> listJob(@RequestBody Map<String, Object> map) {
        return jobDao.listJob(map);
    }

    /**
     * 统计岗位数量
     *
     * @param map 条件
     * @return 数量
     */
    @PostMapping(value = "/countJob")
    public Integer countJob(@RequestBody Map<String, Object> map) {
        return jobDao.countJob(map);
    }

    /**
     * 添加岗位
     *
     * @param jobDO 岗位信息
     * @return 插入结果
     */
    @PostMapping
    public Integer insert(@RequestBody SysJobDO jobDO) {
        return jobDao.insert(jobDO);
    }

    /**
     * 通过id获取岗位信息
     *
     * @param id id
     * @return 岗位信息
     */
    @GetMapping(value = "/{id}")
    public SysJobDO selectOne(@PathVariable("id") Long id) {
        return jobDao.selectById(id);
    }

    /**
     * 修改岗位信息
     *
     * @param jobDO 岗位信息
     * @return 膝盖结果
     */
    @PutMapping
    public Integer update(@RequestBody SysJobDO jobDO) {
        return jobDao.updateById(jobDO);
    }

    /**
     * 删除岗位信息
     *
     * @param ids id
     * @return 结果
     */
    @PostMapping(value = "/ids")
    public Integer remove(@RequestBody Long[] ids) {
        EntityWrapper<SysJobDO> ew = new EntityWrapper<>();
        SysJobDO jobDO = new SysJobDO();
        jobDO.setDelFlag(Global.DEL_FLAG_DELETE);
        ew.setEntity(new SysJobDO());
        EntityWrapper<SysUserJobDO> ewj = new EntityWrapper<>();
        ewj.in("job_id", ids);
        userJobDao.delete(ewj);
        return jobDao.update(jobDO, ew);
    }


    /**
     * 插入用户信息
     *
     * @param sysJobDO 岗位任命信息
     * @return 插入结果
     */
    @PostMapping(value = "/user")
    public ReturnDTO insertUserJob(@RequestBody SysJobDO sysJobDO) {
        Long[] userIds = sysJobDO.getUserIds();
        if (null == sysJobDO.getUpdateId()) {
            EntityWrapper<SysUserJobDO> ew = new EntityWrapper<>(new SysUserJobDO());
            ew.in("user_id", userIds);
            List<SysUserJobDO> userJobDOS = userJobDao.selectList(ew);
            if (userJobDOS == null || userJobDOS.isEmpty()) {
                try {
                    insertUserJob(sysJobDO, userIds);
                    return ReturnDTO.ok();
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReturnDTO.error();
                }
            }
            List<Long> isJob = new ArrayList<>();
            for (SysUserJobDO userJobDO : userJobDOS) {
                isJob.add(userJobDO.getUserId());
            }
            List<Long> noJob = Arrays.asList(userIds);
            List<Long> listA = new ArrayList<>(noJob);
            List<Long> listB = new ArrayList<>(isJob);
            listA.removeAll(listB);
            Long[] nojob = new Long[listA.size()];
            listA.toArray(nojob);
            insertUserJob(sysJobDO, nojob);
            List<SysUserDO> userDOS = userDao.selectBatchIds(isJob);
            StringBuilder sb = new StringBuilder("用户：");
            for (SysUserDO userDO : userDOS) {
                sb.append(userDO.getName()).append("，");
            }
            sb.append("已经任命了岗位，是否重新任命?");
            return ReturnDTO.status(200, sb.toString(), isJob);
        } else {
            try {
                EntityWrapper<SysUserJobDO> ew = new EntityWrapper<>(new SysUserJobDO());
                ew.in("user_id", userIds);
                userJobDao.delete(ew);
                insertUserJob(sysJobDO, userIds);
                return ReturnDTO.ok();
            } catch (Exception e) {
                e.printStackTrace();
                return ReturnDTO.error();
            }
        }
    }

    /**
     * 用户列表
     *
     * @param map 条件
     * @return 结果
     */
    @JsonView(View.AjaxData.class)
    @PostMapping(value = "/userList")
    public List<SysUserDO> selectUserList(@RequestBody Map<String, Object> map) {
        return userJobDao.selectUserList(map);
    }

    /**
     * 统计数量
     *
     * @param map 条件
     * @return 数量
     */
    @PostMapping(value = "/userCount")
    public Integer countUserList(@RequestBody Map<String, Object> map) {
        return userJobDao.countUserList(map);
    }

    @DeleteMapping(value = "/user/{userId}")
    public Integer removeUser(@PathVariable("userId") Long userId) {
        EntityWrapper<SysUserJobDO> ew = new EntityWrapper<>(null);
        ew.eq("user_id", userId);
        return userJobDao.delete(ew);
    }

    private void insertUserJob(@RequestBody SysJobDO sysJobDO, Long[] userIds) {
        for (Long userId : userIds) {
            SysUserJobDO userJobDO = new SysUserJobDO();
            userJobDO.setJobId(sysJobDO.getId());
            userJobDO.setUserId(userId);
            userJobDO.setCreateId(sysJobDO.getCreateId());
            userJobDao.insert(userJobDO);
        }
    }
}
